<?php

class Application_Model_CountryMapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Country');
		}
		return $this->_dbTable;
	}
	
	public function insertAll(Application_Model_Country $obj)
    {
        $data = array(
            'abbrev'   => $obj->getAbbrev(),
            'country_name' => $obj->getCountry_name()
        );
        $this->getDbTable()->insert($data);
    }
    
	public function updateAll(Application_Model_Country $obj)
    {
    	$db = $this->getDbTable();
    	
        $data = array(
        	'abbrev'   => $obj->getAbbrev(),
            'country_name' => $obj->getCountry_name()
        );
        $db->update($data,array('abbrev = ?' => $obj->getAbbrev()));
    }
    
	public function findByResult($select){
		$db = $this->getDbTable();
    	$resultSet = $db->fetchAll($select);
        $entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Country();
			$entry->setAbbrev($row->abbrev)
				->setCountry_name($row->country_name);
			$entries[] = $entry;
		}
		return $entries;
    }
        
	public function findAll()
    {
    	$db = $this->getDbTable();
        $select = $db->select()->from('country');
    	return $this->findByResult($select);
    }
    
	public function findByAbbrev($abbrev)
    {
    	if($abbrev != null){
	    	$db = $this->getDbTable();
	        $select = $db->select()->from('country')
	             ->where('abbrev = ?', $abbrev);
	    	
	    	return $this->findByResult($select);
    	}
    }
}

